import {callFunctionWithRetry} from '../../utils/util'

const app = getApp()

Page({
  data: {
    debug: "",
    page: 0,
    enable: false,
    loading: false,
    noMore: false,
    initLoading: true,
    cardInfo: [],
    // 发布
    motto: 'Light Band',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
  },
  onReachBottom() {
    console.log("Refreshing!!!!");

    if (this.loading || this.noMore) return
    this.setData({ page: this.data.page + 1 }, () => {
      this.refresh()
    })
  },
  // 生命周期
  async onShow() {
    this.setData({
      debug: "onShow",
    })
    if(app.globalData.needRefresh){
      this.setData({
        debug: "needRefresh",
      })
      this.refreshTotally()
      app.globalData.needRefresh = false
    }else{
      this.setData({
        debug: "no need to refresh"
      })
    }
    
    const nav = this.selectComponent('#nav_bar')
    console.log('Find nav:' + nav)
    if(nav){
      nav.updateSearchValue()
    }
  },
  onSearch(e) {
    this.refreshTotally()
  },
  onSearchClear(e) {
    app.globalData.queryInfo.q = ''
    app.globalData.queryInfo.nps = {
      status: [false, false],
      min: 0,
      max: 20.0
    }
    this.refreshTotally()
  },
  onCardClick(e){
    console.log("clicked the card:" , e )
    wx.navigateTo({
      url: '/pages/song/index',
      success(res){
        res.eventChannel.emit('acceptSongItem', e.target.dataset.item)
      }
    })
  },
  onLoad(option) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true,
      });
    }
  },
  scrollTop: -1,
  onPageScroll(e){
    this.scrollTop = e.detail.scrollTop
    console.log("Scroll Top:" + this.scrollTop)
  },
  onRefresh(){
    if(this.scrollTop > 10)
      return
    this.refreshTotally();
  },
  refreshTotally() {
    this.setData({page:0, loading: false, noMore: false});
    this.refresh();
  },
  async refresh() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    this.loading = true;
    let _this = this;

    console.log("q is:", app.globalData.queryInfo)
    callFunctionWithRetry(
      'getBeatSaverLatest',
      {
        page: this.data.page,
        q: app.globalData.queryInfo.q,
        nps: app.globalData.queryInfo.nps
      }).then(res=>{
        console.log('Result:', res.result);
        wx.hideLoading()

        _this.setData({initLoading: false});

        if(_this.data.page == 0){
          _this.setData({cardInfo: []})
        }
        
        _this.setData({
          enable: false,
          cardInfo: _this.data.cardInfo.concat(res.result.data.docs)
        })
        _this.loading = false;
      }).catch(err=>{
        console.log('Failed!', err);
        _this.loading = false;
      })
  }
});
